import CryptoJS from 'crypto-js'

// 生成随机AES秘钥
export function createKey(length = 64) {
  return CryptoJS.lib.WordArray.random(length).toString()
}

/**
 * 通用对称加密数据(即使是相同的key多次加密的结果也是不一样的)
 * @param data 需要加密的数据
 * @param algorithm 加密算法
 * @param key 密钥
 * @returns 加密字符串
 */
export function encrypt(
  data: string,
  algorithm: 'AES' | 'DES' | 'Blowfish' | 'RC4' | 'RC4Drop' | 'Rabbit' | 'RabbitLegacy' | 'TripleDES' = 'AES',
  key: string = 'qwertyuiopasdfghjklzxcvbnm',
): string {
  return CryptoJS[algorithm].encrypt(data, key).toString()
}
/**
 * 通用对称解密数据
 * @param encryptedData 加密字符串
 * @param algorithm 加密算法
 * @param key 密钥
 * @returns 解密后的原始数据
 */
export function decrypt(
  encryptedData: string,
  algorithm: 'AES' | 'DES' | 'Blowfish' | 'RC4' | 'RC4Drop' | 'Rabbit' | 'RabbitLegacy' | 'TripleDES' = 'AES',
  key: string = 'qwertyuiopasdfghjklzxcvbnm',
): string {
  return CryptoJS[algorithm].decrypt(encryptedData, key).toString(CryptoJS.enc.Utf8)
}

// 非对称加密，需要秘钥
export function encryptNoDecrypt(
  data: string,
  algorithm: 'HmacMD5' | 'HmacRIPEMD160' | 'HmacSHA1' | 'HmacSHA224' | 'HmacSHA256' | 'HmacSHA3' | 'HmacSHA384' | 'HmacSHA512' = 'HmacMD5',
  key: string,
) {
  return CryptoJS[algorithm](data, key).toString()
}

// 非对称加密不需要秘钥
export function encryptNoDecryptNoKey(
  data: string,
  algorithm: 'MD5' | 'RIPEMD160' | 'SHA1' | 'SHA224' | 'SHA256' | 'SHA3' | 'SHA384' | 'SHA512' = 'MD5',
) {
  return CryptoJS[algorithm](data).toString()
}
